package Classic150;

import Tree.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class 填充每个节点的下一个右侧节点指针2 {
    public TreeNode connect(TreeNode root) {
        /*
            层序遍历经典用法，可以优化，参考题解
         */
        if (root == null) return null;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size-- > 0) {
                TreeNode node = queue.poll();
                if (size != 0) node.next = queue.peek();
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
        }
        return root;
    }
}
